package com.may.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * @program: netty-websocket
 * @description:
 * @author: Bobby.Ma
 * @create: 2020-11-23 23:35
 **/
@Slf4j
// 这里 TextWebSocketFrame 类型，表示一个文本帧(frame)
public class SocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("服务器收到消息:{}", msg.text());
    }

    // 当 web 客户端连接后，触发方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // asLongText 是唯一的 ， asShortText 不一定唯一
        log.info("连接建立 {}", ctx.channel().id().asLongText());
//        ctx.channel().writeAndFlush(new TextWebSocketFrame("报价消息"));
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("连接断开 {}", ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("连接异常 {}", cause.getMessage());
        ctx.close();
    }

}
